#include "socket_util.h"
#include "connection_handler.h"
#include "thread_pool.h"
#include "logger.h"
#include "string.h"
#include <sys/epoll.h>
#include <vector>
#include <memory>

const int MAX_EVENTS = 100;
const int PORT = 8080;

int main()
{
    Logger::init("server.log", LogLevel::INFO);
    Logger::info("Starting FTP server on port " + std::to_string(PORT));

    try
    {
        int server_fd = create_server_socket(PORT);
        SocketRAII server_raii(server_fd);

        int epoll_fd = epoll_create1(0);
        if (epoll_fd == -1)
            throw std::runtime_error("epoll_create1 failed");
        SocketRAII epoll_raii(epoll_fd);

        epoll_event event{};
        event.events = EPOLLIN;
        event.data.fd = server_fd;
        if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &event) == -1)
            throw std::runtime_error("epoll_ctl failed");

        std::vector<epoll_event> events(MAX_EVENTS);
        ThreadPool pool(4); // 4个工作线程

        Logger::info("FTP Server started successfully");

        while (true)
        {
            int num_events = epoll_wait(epoll_fd, events.data(), MAX_EVENTS, -1);
            if (num_events == -1)
            {
                Logger::error("epoll_wait error: " + std::string(strerror(errno)));
                continue;
            }

            for (int i = 0; i < num_events; ++i)
            {
                if (events[i].data.fd == server_fd)
                {
                    // 处理新连接
                    sockaddr_in client_addr{};
                    socklen_t client_addr_len = sizeof(client_addr);
                    int client_fd = accept(server_fd, (sockaddr *)&client_addr, &client_addr_len);
                    if (client_fd == -1)
                    {
                        Logger::error("accept error: " + std::string(strerror(errno)));
                        continue;
                    }

                    set_nonblocking(client_fd);

                    epoll_event client_event{};
                    client_event.events = EPOLLIN | EPOLLET;
                    client_event.data.fd = client_fd;
                    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &client_event) == -1)
                    {
                        Logger::error("epoll_ctl for client failed");
                        close(client_fd);
                    }
                    const char *response = "220 Welcome to FTP Server\r\n";
                    send(client_fd, response, strlen(response), 0);
                    Logger::info("New client connected: " + std::to_string(client_fd));
                }
                else
                {
                    // 修复 lambda 捕获问题
                    int fd = events[i].data.fd;
                    pool.enqueue([fd]
                                 { handle_connection(fd); });
                }
            }
        }
    }
    catch (const std::exception &e)
    {
        Logger::error("Server fatal error: " + std::string(e.what()));
        return 1;
    }

    return 0;
}